import { Renderer } from './engine/core/renderer.js';
import { Node } from './engine/core/node.js';
import { OrthogonalCamera } from './engine/cameras/orthogonalCamera.js';
import { Background } from './game/background.js'
import { EnemyManager } from './game/enemyManager.js'
import { databus } from './game/databus.js'
import { Player } from './game/player.js'
import { UI } from './game/ui.js'
import { vec3 } from './engine/gl-matrix/index.js'

const renderer = new Renderer({ depth: false, alpha: false }, canvas);

export default class Main {
    constructor() {
        this.init();
    }

    init() {
        const scene = new Node();
        const camera = new OrthogonalCamera(
            -databus.rightX,//left
            databus.rightX,//right
            -databus.topY,//bottom
            databus.topY,//top
            0.1, 1000
        );
        camera.translation = vec3.fromValues(0, 0, 1.0);
        databus.mainCamera = camera;

        let background = new Background();
        scene.add(background);

        let enemyManager = new EnemyManager();
        scene.add(enemyManager);

        let player = new Player();
        scene.add(player);

        let ui = new UI();
        scene.add(ui);

        this.ui = ui;
        this.scene = scene;
        this.camera = camera;

        this.bindAnimate = this.animate.bind(this);
        this.touchHandler = this.touchEventHandler.bind(this)
        this.animate();
    }

    restart() {
        databus.gameOver = false;
        databus.score = 0;
        renderer.clear();

        canvas.removeEventListener(
            'touchstart',
            this.touchHandler
        );

        this.hasTouchstart = false;
        this.init();
    }

    animate() {
        requestAnimationFrame(this.bindAnimate);

        if (databus.gameOver && !this.hasTouchstart) {
            this.hasTouchstart = true;
            canvas.addEventListener('touchstart', this.touchHandler);
        }

        renderer.render(this.scene, this.camera, databus.gameOver);
    }

    touchEventHandler(e) {
        if (!databus.gameOver) return;

        const x = e.touches[0].clientX
        const y = e.touches[0].clientY

        const area = this.ui.btnArea;

        if (x >= area.startX
            && x <= area.endX
            && y >= area.startY
            && y <= area.endY) this.restart();
    }
}
